<template>
  <page-card title="公告管理"
             :sub-title="!this.$route.query.id ? '新增':'编辑'"
             :need-back="true">

    <a-form :form="form"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol">
      <a-form-item label="ID"
                   v-show="false">
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item label="标题">
        <a-input allowClear
                 placeholder="请输入标题"
                 :maxLength="100"
                 v-decorator="['title', {
                   rules: [{
                     required: true, transform: value => value ? value.trim() : '', message: '请输入标题'
                   }]
                 }]" />
      </a-form-item>
      <a-form-item label="作者">
        <a-input allowClear
                 placeholder="请输入作者"
                 :maxLength="50"
                 v-decorator="['author', {
                   rules: [{
                     required: true, transform: value => value ? value.trim() : '', message: '请输入作者'
                   }]
                 }]" />
      </a-form-item>
      <a-form-item label="分类"
                   required>
        <a-radio-group name="type"
                       v-decorator="['type', {
                         rules: [{
                           required: true, message: '请选择分类'
                         }]
                       }]"
                       @change="radiaoChangeType">
          <a-radio v-for="(item, index) in antypeList"
                   :key="index"
                   :value="item.dictKey">
            {{ item.dictValue }}
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="selectTypeVal=='2'"
                   label="接收单位"
                   required>
        <a-radio-group name="groupId"
                       v-decorator="['groupId', {
                         rules: [{
                           required: true, message: '请选择分类'
                         }]
                       }]"
                       @change="radiaoChange">
          <a-radio v-for="(item, index) in typeList"
                   :key="index"
                   :value="item.groupsId">
            {{ item.groupName }}
          </a-radio>
        </a-radio-group>

        <!-- <CheckUnitAntD @valueChange="unitChange"
                       :disabled="groupId!=-1"
                       :value="unitIdsArr"></CheckUnitAntD> -->
        <ZSelectUnit @change="unitChange"
                     :disabled="groupId!=-1"
                     :value="unitIdsArr"></ZSelectUnit>
      </a-form-item>
      <a-form-item label="图片">
        <z-image-uploader :isQuery="imgUpload.isQuery"
                          :showUploadList="imgUpload.showUploadList"
                          :parentId="$route.query.id"
                          :bucketName="imgUpload.bucketName"
                          :systemName="imgUpload.systemName"
                          :limit="imgUpload.limit"
                          :prop="imgUpload.imgList"
                          :configGroup="imgUpload.configGroup"
                          ref="imgUploader"
                          v-model="imgUpload.imgList" />
      </a-form-item>
      <a-form-item label="内容"
                   required>
        <div ref="content" style="width:816px;">
        </div>
      </a-form-item>
      <a-form-item label="有效时间">
        <a-date-picker placeholder="请输入公告有效时间"
                       style="width: 100%;"
                       format="YYYY-MM-DD"
                       v-decorator="['deadlineTime', {
                         rules: [{
                           required: false, message: '请输入公告有效时间'
                         }]
                       }]" />
      </a-form-item>
      <a-form-item label="附件">
        <z-file-uploader :isQuery="fileUpload.isQuery"
                         :showUploadList="fileUpload.showUploadList"
                         :parentId="$route.query.id"
                         :bucketName="fileUpload.bucketName"
                         :systemName="fileUpload.systemName"
                         :limit="fileUpload.limit"
                         :prop="fileUpload.fileList"
                         :configGroup="fileUpload.configGroup"
                         ref="fileUploader"
                         v-model="fileUpload.fileList" />
      </a-form-item>
    </a-form>

    <a-form-item label=" "
                 :colon="false">
      <div style="text-align:center">
        <a-button type="primary"
                  action
                  @click="handleSave">发布</a-button>
      </div>
    </a-form-item>

    <a-modal v-model="modalUnitVisible"
             :title="modalUnitTitle"
             style="z-index:10003;height:500px"
             ok-text="确定"
             cancel-text="取消"
             @ok="saveUnit">
      <div class="border">

        <a-tree @check="checkUnit"
                @select="selectUnit"
                @expand="expand"
                style="height:500px;overflow:auto;"
                v-model="checkedKeysUnit"
                :selectedKeys="selectedKeys"
                :checkStrictly="checkStrictly"
                :expandedKeys="expandedKeys"
                checkable
                :showIcon="true"
                :tree-data="treeDataUnit">
          <a-icon slot="switcherIcon"
                  type="caret-down" />
          <a-icon slot="clazz"
                  type="appstore" />
          <a-icon slot="unit"
                  type="home" />
          <a-icon slot="dept"
                  type="bank" />
          <template slot="custom"
                    slot-scope="item">
            <span>{{ item.treeTitle }} </span>
            <span v-if="!item.isLeaf">
              <span v-if="!item.checked"
                    title="全选">
                <a-icon type="plus-square"
                        @click="addClick(item)" />
              </span>
              <span v-else
                    title="取消全选">
                <a-icon type="minus-circle"
                        @click="cancelClick(item)" />
              </span>
            </span>

          </template>
        </a-tree>
      </div>
    </a-modal>
  </page-card>
</template>

<script>
import E from 'wangeditor'
// import {
//   ImageUploader,
//   FileUploader,
//   CheckUnitAntD
// } from 'zenith-vue-components'
import { http } from '@zh/common-utils/http'
import { saveOrUpdate, getById, queryUnit } from '../../api/announcement/index'
import { unitTreeV2, getUnitIds } from '../../api/unit/index'
import { getGroupList, getGroupAndUnitsById } from '../../api/unit/group'
import { getCode } from '../../api/dictionary/index'
import { ZSelectUnit } from '@zh/components-ant'

export default {
  components: {
    // ImageUploader,
    // FileUploader,
    // CheckUnitAntD,
    ZSelectUnit,
    E
  },
  data () {
    return {
      modeTypeVisible: false,
      antypeList: [],
      typeList: [],
      groupId: '',
      imgUpload: {
        limit: 1,
        editor: null,
        parentId: '',
        imgList: [], // 图片列表集合
        isQuery: false, // 当此参数为true时表示其功能不可上传图片
        showUploadList: true, // 是否显示图片列表
        bucketName: 'zongheng-system', // 当前归属系统所在的空间名称
        systemName: 'zongheng-system', // 归属系统名称
        configGroup: 'zongheng-img-announcement'
      },
      fileUpload: {
        limit: 99,
        editor: null,
        parentId: '',
        fileList: [], // 图片列表集合
        isQuery: false, // 当此参数为true时表示其功能不可上传图片
        showUploadList: true, // 是否显示图片列表
        bucketName: 'zongheng-system', // 当前归属系统所在的空间名称
        systemName: 'zongheng-file-announcement', // 归属系统名称
        configGroup: 'zongheng-file-announcement'
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 12 }
      },
      typeOptions: [
        {
          label: '字典参数',
          value: '1'
        },
        {
          label: '业务参数',
          value: '2'
        }
      ],
      data: [],
      form: this.$form.createForm(this),
      checkedKeysUnit: {
        checked: [],
        halfChecked: []
      },
      selectedKeys: [],
      expandedKeys: [],
      treeDataUnit: [],
      modalUnitVisible: false,
      modalUnitTitle: null,
      checkStrictly: true,
      unitIds: [],
      unitNames: [],
      unitIdsArr: [],
      selectTypeVal: ''
    }
  },
  mounted () {
    this.getCode()
    this.groupsList()
    const id = this.$route.query.id
    if (id) {
      this.getById(id)
      this.getCheckedKeys()
    }
    this.editor = new E(this.$refs.content)
    this.editor.config.menus = [
      'bold', // 粗体
      'fontSize', // 字号
      'fontName', // 字体
      'italic', // 斜体
      'underline', // 下划线
      'strikeThrough', // 删除线
      'foreColor', // 文字颜色
      'link', // 插入链接
      'list', // 列表
      'justify', // 对齐方式
      'quote', // 引用
      // 'image', // 插入图片
      'location' // 位置
    ]
    this.editor.config.onchange = (html) => {
      this.$emit('input', html)
    }
    this.editor.config.uploadImgServer = http.getUploadURL
    this.editor.config.uploadImgMaxSize = 10 * 1024 * 1024 // 将图片大小限制为 10M
    this.editor.config.uploadFileName = 'file' // 后端接受上传文件的参数名
    this.editor.config.uploadImgMaxLength = 1 // 限制一次最多上传 1 张图片
    this.editor.config.showLinkImg = false // 隐藏网络图片上传
    this.editor.config.pasteFilterStyle = false // 手动关闭wangeditor粘贴样式的过滤
    this.editor.config.uploadImgParams = {
      bucketName: 'zongheng-system', // 当前归属系统所在的空间名称
      systemName: 'ykz-announcement', // 归属系统名称
      configGroup: 'ykz_system_announcement'
    }
    this.editor.config.uploadImgHooks = {
      fail: (xhr, editor, result) => {
        // 插入图片失败回调
      },
      success: (xhr, editor, result) => {
        // 图片上传成功回调
      },
      timeout: (xhr, editor) => {
        // 网络超时的回调
      },
      error: (xhr, editor) => {
        // 图片上传错误的回调
      },
      // 回显
      customInsert: (insertImg, result, editor) => {
        let key = result.data.key
        let url = http.getDownloadURL + key
        insertImg(url)
      }
    }
    this.editor.create()
  },
  methods: {
    radiaoChangeType (e) {
      this.selectTypeVal = e.target.value
    },
    radiaoChange (e) {
      const checkedValue = e.target.value
      this.groupId = checkedValue
      const unitSelect = this.typeList.filter((item) => {
        return checkedValue == item.groupsId
      })
      if (unitSelect.length > 0) {
        let unitGroupsList = unitSelect[0].unitGroupsList
        this.unitIdsArr = []
        unitGroupsList.forEach((item) => {
          this.unitIdsArr.push(item.unitId)
        })
      }
    },
    getCurrentStyle (current, today) {
      const style = {}
      if (current.date() === 1) {
        style.border = '1px solid #1890ff'
        style.borderRadius = '50%'
      }
      return style
    },
    unitChange (value) {
      this.unitIdsArr = []
      value.map((item) => {
        this.unitIdsArr.push(item)
      })
    },
    groupsList () {
      const _this = this
      getGroupList({}).then((response) => {
        _this.typeList = response
        let obj = { groupsId: '-1', groupName: '自定义', unitGroupsList: [] }
        _this.typeList.push(obj)
      })
    },
    getCode () {
      const _this = this
      getCode('ANOUNCEMENT_TYPE').then((response) => {
        _this.antypeList = response
      })
    },
    getById (id) {
      getById(id).then((response) => {
        const values = {}
        this.selectTypeVal = response.type
        this.unitIdsArr = [...response.unitIds]
        for (const k in this.form.fieldsStore.fieldsMeta) {
          // eslint-disable-next-line no-prototype-builtins
          response.hasOwnProperty(k) && (values[k] = response[k])
        }
        this.editor.txt.html(response.content)
        if (values.dictType == '') {
          values.dictType = []
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(values)
          this.form.setFieldsValue({ groupId: response.groupId })
        })
      })
    },
    handleSave () {
      const _this = this
      // return
      this.form.validateFieldsAndScroll((err, values) => {
        if (err) {
          return
        }
        if (values.title) {
          values.title = values.title.trim()
        }
        if (values.author) {
          values.author = values.author.trim()
        }
        for (let i = 0; i < _this.typeList.length; i++) {
          if (values.dictType == _this.typeList[i].dictKey) {
            values.dictName = _this.typeList[i].dictValue
            break
          }
        }
        values.content = _this.editor.txt.html()
        if (this.selectTypeVal == '2' && this.unitIdsArr.length == 0) {
          this.message.warn('请选择接收单位')
          return
        }
        if (!values.content) {
          this.message.warn('请输入公告内容')
          return
        }

        if (_this.imgUpload.imgList.length > 0) {
          values.img = _this.imgUpload.imgList[0].url
        }
        values.imgList = _this.imgUpload.imgList
        values.fileList = _this.fileUpload.fileList
        values.unitIds = [...new Set(this.unitIdsArr)]
        saveOrUpdate(values).then((response) => {
          // _this.message.success(values.id ? '公告修改发布成功' : '公告发布成功')
          _this.$router.go(-1)
        })
      })
    },
    appUnit () {
      let topId
      const loginUser = this.$store.getLoginUser()
      if (loginUser.account === 'admin') {
        topId = 0
      } else {
        topId = loginUser.depts[0].deptId
      }
      this.modalUnitVisible = true
      this.showtree = true
      this.unitSearch = ''
      this.modalUnitTitle = '机构授权'
      // this.checkedKeysUnit.checked = []
      // this.expandedKeys = []
      // this.treeDataUnit = []
      // this.getCheckedKeys()
      this.initTree(topId)
    },
    getCheckedKeys () {
      let anId = this.$route.query.id
      if (anId) {
        queryUnit(anId).then((response) => {
          this.expandedKeys = response
          this.checkedKeysUnit.checked = response
        })
      }
    },
    initTree (topId) {
      unitTreeV2(topId).then((response) => {
        this.treeDataUnit = response
        this.treeDataUnit.forEach((item) => {
          this.setTreeData(item)
        })
      })
    },
    setTreeData (item) {
      item.scopedSlots = {
        title: 'custom',
        icon: 'icon'
      }
      let children = item.children
      if (children && children.length > 0) {
        children.forEach((data) => {
          this.setTreeData(data)
        })
      }
    },
    checkUnit (checkedKeys, e) {
      this.checkedKeysUnit.checked = checkedKeys.checked
      this.selectedKeys = checkedKeys.checked
    },
    selectUnit (selectedKeys, info) {
      // let selectData = info.node.dataRef
      // if (this.checkedKeysUnit.checked.indexOf(selectData.key) >= 0) {
      //   this.getClick(selectData, 'del')
      // } else {
      //   this.getClick(selectData, 'add')
      // }
      // this.selectedKeys = selectedKeys
    },
    expand (expandedKeys, info) {
      // let data = info.node.dataRef
      // if (info.expanded) {
      //   expandedKeys = this.getExpanded(expandedKeys, data, 'add')
      // } else {
      //   expandedKeys = this.getExpanded(expandedKeys, data, 'del')
      // }

      this.expandedKeys = expandedKeys
    },
    getExpanded (expandedKeys, data, type) {
      if (type === 'add') {
        if (expandedKeys.indexOf(data.key) === -1) {
          expandedKeys.push(data.key)
        }
      } else {
        if (expandedKeys.indexOf(data.key) >= 0) {
          expandedKeys = expandedKeys.filter((k) => k !== data.key)
        }
      }
      let children = data.children
      if (children && children.length > 0) {
        children.forEach((item) => {
          expandedKeys = this.getExpanded(expandedKeys, item, type)
        })
      }
      return expandedKeys
    },
    addClick (item) {
      this.getClick(item, 'add')
      // this.selectedKeys = this.checkedKeysUnit.checked
    },
    cancelClick (item) {
      this.getClick(item, 'del')
      this.selectedKeys = []
    },
    getClick (data, type) {
      if (type === 'add') {
        if (this.checkedKeysUnit.checked.indexOf(data.key) === -1) {
          if (data.disabled === false) {
            this.checkedKeysUnit.checked.push(data.key)
          }
        }
        const addchildren = data.children
        if (addchildren && addchildren.length > 0) {
          for (let i = 0; i < addchildren.length; i++) {
            const addData = addchildren[i]
            this.getClick(addData, 'add')
          }
        }
      } else {
        if (this.checkedKeysUnit.checked.indexOf(data.key) >= 0) {
          if (data.disabled === false) {
            this.checkedKeysUnit.checked = this.checkedKeysUnit.checked.filter(
              (k) => k !== data.key
            )
          }
        }
        const delchildren = data.children
        if (delchildren && delchildren.length > 0) {
          for (let i = 0; i < delchildren.length; i++) {
            const delData = delchildren[i]
            this.getClick(delData, 'del')
          }
        }
      }
    },
    saveUnit () {
      const _this = this
      _this.modalUnitVisible = false
      if (_this.checkedKeysUnit.checked.length > 0) {
        let param = {}
        param.unitIds = _this.checkedKeysUnit.checked
        getUnitIds(param).then((res) => {
          _this.form.setFieldsValue({
            unitNames: res.data
          })
        })
      } else {
        _this.form.setFieldsValue({
          unitNames: ''
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
::v-deep .w-e-menu {
  z-index: 2 !important;
}
::v-deep .w-e-text-container {
  z-index: 1 !important;
}
::v-deep .w-e-toolbar {
  z-index: 1 !important;
}
</style>
